#!/bin/bash
#拉取镜像
#docker pull nginx:latest
FILE_COUNT=$#
if((FILE_COUNT!=1)); then
    echo ">>> 错误：未传递端口！"
    echo "  用法：nginx_docker.sh port"
    exit;
fi
PORT=$1

#=========清除=========
# 删除已有容器
echo ">>> 删除原有nginx容器"
docker ps -a | grep nginx | awk '{print($1)}' | xargs -n 1 docker rm -f

# 全局路径变量
NGINX_PATH=/opt/module/nginx
# 删除已有数据目录
if [ -d "$NGINX_PATH" ]; then
    echo ">>> 删除$NGINX_PATH目录下所有数据"
    rm -rf $NGINX_PATH
fi
#=========安装=========
# 创建数据多个子目录
mkdir -p $NGINX_PATH
mkdir $NGINX_PATH/{"html","logs","conf"}

echo ">>> 开始启动容器，并复制配置文件"
#第一步(预启动，只为拷贝文件)：
docker run -d \
    --privileged=true \
    -v /etc/localtime:/etc/localtime:ro \
    -p 80:80 \
    --name nginx \
    -v $NGINX_PATH/html:/usr/share/nginx/html \
    -v $NGINX_PATH/logs:/var/log/nginx \
    nginx
#第二步（复制配置文件nginx.conf，conf.d）：
docker cp nginx:/usr/share/nginx/html $NGINX_PATH
docker cp nginx:/etc/nginx/nginx.conf $NGINX_PATH/conf
docker cp nginx:/etc/nginx/conf.d $NGINX_PATH/conf

echo ">>> 停止旧容器，启动新容器"
#第三步：文件copy成功后 把nginx容器先删除掉
docker rm -f nginx
#第四步：
docker run -d -p $PORT:80 --name nginx \
-v $NGINX_PATH/html:/usr/share/nginx/html \
-v $NGINX_PATH/conf/nginx.conf:/etc/nginx/nginx.conf \
-v $NGINX_PATH/conf/conf.d:/etc/nginx/conf.d \
-v $NGINX_PATH/logs:/var/log/nginx \
nginx

#第五步：
# 生成错误页面
sudo cat >$NGINX_PATH/html/index.html<<EOF
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<h2>访问：<a href="https://gitee.com/lovelemoncat/" title="Lovelemoncat主页">Lovelemoncat</a>主页</h2>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
EOF
# 生成错误页面
sudo cat >$NGINX_PATH/html/50x.html<<EOF
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Error</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>An error occurred.</h1>
<h2>访问：<a href="https://gitee.com/lovelemoncat/" title="Lovelemoncat主页">Lovelemoncat</a>主页</h2>
<p>Sorry, the page you are looking for is currently unavailable.<br/>
Please try again later.</p>
<p>If you are the system administrator of this resource then you should check
the <a href="http://nginx.org/r/error_log">error log</a> for details.</p>
<p><em>Faithfully yours, nginx.</em></p>
</body>
</html>
EOF



